const redis = require('../core/redis/redisClient.js')
const ApiResponseUtil = require('../util/ApiResponseUtil.js')

// 处理获取聊天记录
exports.handleChatHistory = async (req, res) => {
    const senderId = req.auth.id
    const { receiverId } = req.query;

    if (!senderId || !receiverId)  return res.send(ApiResponseUtil.error('缺少 senderId 或 receiverId'));

    try {
        const minId = Math.min(Number(senderId), Number(receiverId));
        const maxId = Math.max(Number(senderId), Number(receiverId));
        const chatKey = `private:chat:${minId}:${maxId}`;

        // 拉取最新的 50 条消息
        const results = await redis.lRange(chatKey, 0, 49); 

        // 解析每条 JSON 字符串，得到对象数组
        const chatHistory = results.map(message => JSON.parse(message));

        // 按时间倒序
        chatHistory.reverse();

        res.send(ApiResponseUtil.success(200, '获取聊天记录成功', chatHistory))
    } catch (error) {
        console.log(error.message)
        res.send(ApiResponseUtil.error(500, '获取聊天记录失败'))
    }
}

// 处理获取群聊记录
exports.handleGroupChatHistory = async (req, res) => {
    const { groupId } = req.query;

    if (!groupId) return res.send(ApiResponseUtil.error('缺少 groupId'));

    try {
        const chatKey = `group:chat:${groupId}`;

        // 拉取最新的 50 条消息
        const results = await redis.lRange(chatKey, 0, 49); 

        // 解析每条 JSON 字符串，得到对象数组
        const chatHistory = results.map(message => JSON.parse(message));

        // 按时间倒序
        chatHistory.reverse();

        res.send(ApiResponseUtil.success(200, '获取群聊记录成功', chatHistory))
    } catch (error) {
        console.log(error.message)
        res.send(ApiResponseUtil.error(500, '获取群聊记录失败'))
    }
}
